package com.emmy.walnut.presenter;

import android.os.Handler;
import android.os.Message;

import com.emmy.walnut.app.AppDatabase;
import com.emmy.walnut.constant.AppConstant;
import com.emmy.walnut.model.Label;
import com.emmy.walnut.model.Record;
import com.emmy.walnut.model.User;
import com.emmy.walnut.presenter.iface.LoginPIface;
import com.emmy.walnut.util.MD5Util;
import com.emmy.walnut.util.PreferenceUtil;
import com.emmy.walnut.view.iface.LoginIface;

import java.util.ArrayList;

public class LoginPresenter implements LoginPIface {

    private LoginIface loginIface;

    public LoginPresenter(LoginIface loginIface){
        this.loginIface = loginIface;
    }

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what){
                case AppConstant.LOGIN_SUCESS:
                    loginIface.loginSuccess();
                    return true;
                case AppConstant.LOGIN_FAIL:
                    loginIface.loginFailed("用户名或密码错误");
                    return true;
            }
            return false;
        }
    });


    @Override
    public void login(final String username, final String password) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                User user = AppDatabase.getInstance().userDao().query(username);
                if (user!=null&&user.getPassword().equals(MD5Util.md5(password))){
                    //操作内存数据
                    AppConstant.username = username;
                    if (user.getAvatar()!=null&&!user.getAvatar().equals("")){
                        AppConstant.avatar_path = user.getAvatar();
                    }
                    AppConstant.activities =(ArrayList<Label>)
                            AppDatabase.getInstance().labelDao().getLabelWithUser(username);
                    AppConstant.undoneRecords = (ArrayList<Record>)
                            AppDatabase.getInstance().recordDao().getUndoneRecordWithUser(username);
                    //操作PreferenceUtil数据
                    PreferenceUtil.putString("username", username);
                    PreferenceUtil.putBoolean("isLogin", true);
                    PreferenceUtil.apply();
                    //发送消息给主线程
                    Message.obtain(handler, AppConstant.LOGIN_SUCESS).sendToTarget();
                }else{
                    //发送消息给主线程
                    Message.obtain(handler, AppConstant.LOGIN_FAIL).sendToTarget();
                }
            }
        }).start();
//        JSONObject jsonObject = new JSONObject();
//        try {
//            jsonObject.put("nickname",username);
//            jsonObject.put("password", password);
//        }catch (JSONException jsonException){
//            jsonException.printStackTrace();
//        }
//
//        RequestBody requestBody = RequestBody.create(MediaType.get(AppConstant.MEDIA_JSON_TYPE), jsonObject.toString());
//        RetrofitHelper.getInstance().serviceApi().login(requestBody)
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new Subscriber<GeneralResult>() {
//                    @Override
//                    public void onCompleted() {
//
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
//
//                    }
//
//                    @Override
//                    public void onNext(GeneralResult loginAndRegResult) {
//                        if (loginAndRegResult.getSuccess())
//                            loginIface.loginSuccess(loginAndRegResult.getUUid(), loginAndRegResult.getAccessKey());
//                        else
//                            loginIface.loginFailed(loginAndRegResult.getError_msg());
//                    }
//                });
    }


    @Override
    public void loginWithoutAuthen() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (!PreferenceUtil.getString("avatarPath").equals("")){
                    AppConstant.avatar_path = PreferenceUtil.getString("avatarPath");
                }
                AppConstant.username = PreferenceUtil.getString("username");
                AppConstant.activities =(ArrayList<Label>)
                        AppDatabase.getInstance().labelDao().getLabelWithUser(AppConstant.username);
                AppConstant.undoneRecords = (ArrayList<Record>)
                        AppDatabase.getInstance().recordDao().getUndoneRecordWithUser(AppConstant.username);
                loginIface.loginWithoutAuth();
            }
        }).start();
/*        String timestamp = String.valueOf(System.currentTimeMillis());
        String token = MD5Util.md5(uuid+accessKey+timestamp+AppConstant.SALT_VALUE);
        RetrofitHelper.getInstance().serviceApi().tradeIn(accessKey, timestamp, token, uuid)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<GeneralResult>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(GeneralResult generalResult) {
                        if (generalResult.getSuccess())
                            loginIface.continueLogin(generalResult.getUUid(), generalResult.getAccessKey());
                        else
                            loginIface.reLogin();
                    }
                });*/
    }
}
